package adv42;

import java.util.Random;

/**
 * @author oldliu
 * @since 1.0
 */
//取钱人
public class Taker2 extends Thread {
    private final Account ac;

    public Taker2(String name, Account ac) {
        super(name);
        this.ac = ac;
    }

    @Override
    public void run() {
        Random r = new Random();
        while (true) {
            int qu = r.nextInt(200);
            System.out.println(super.getName() + "准备取钱：" + qu + "元，余额是" + ac.getMoney());
            synchronized (ac) {
                while (ac.getMoney() < qu) {
                    System.out.println(super.getName() + "发现钱不够，等着");
                    try {
                        ac.wait();
                        System.out.println(super.getName() + "被喊醒了，看一下余额：" + ac.getMoney() + "元");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                ac.take(qu);
                System.out.println(super.getName() + "取钱：" + qu + "元成功，余额是" + ac.getMoney());
            }
        }
    }

    public static void main(String[] args) {
//        StringBuilder s=null;
//        s.append("333");
//        StringBuffer s2=null;
//        s2.append("");
        Account account = new Account("老杨", 4000);
        Taker2 t1 = new Taker2("杨旭", account);
        Taker2 t2 = new Taker2("小杨", account);
        Taker2 t3 = new Taker2("老杨", account);
        t1.start();
        t2.start();
        t3.start();
    }
}
